﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using AuthorizationServer.Providers;
using Owin.Security.Custom.Providers;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Serializer;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Owin.Security.Custom.DataProtection;

namespace AuthorizationServer
{
    public partial class Startup
    {
        static Startup()
        {
            UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/api/Token"),
                Provider = new SampleCompleteOAuthProvider(UserManagerFactory),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true,
                AccessTokenProvider = new BaseAccessTokenProvider(),
                AccessTokenFormat = new SecureDataFormat<AuthenticationTicket>(
                    new TicketSerializer(),
                    new AesDataProtector(),
                    new Base64TextEncoder())
            };

            CreateAdmin();
        }

        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
            
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();
        }

        private static void CreateAdmin()
        {
            IdentityDbContext db = new IdentityDbContext();
            var adminRole = db.Roles.Where(x => x.Name == "Admin");

            if (adminRole.Count() == 0)
            {
                RoleManager<IdentityRole> rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
                IdentityRole role = new IdentityRole("Admin");
                var userRoles = rm.Create(role);
            }

            var adminUser = db.Users.Where(x => x.UserName == "Admin");

            if (adminUser.Count() == 0)
            {
                UserManager<IdentityUser> um = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
                IdentityUser user = new IdentityUser("Admin");
                var u = um.Create(user,"password");
                um.AddToRole(um.Find("Admin","password").Id, "Admin");
            }
        }
    }
}
